package com.ds.admin.config.thread;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Description: 线程池配置 Author: fs Date: 2023-04-09
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig implements AsyncConfigurer {

	/**
	 * 项目共用线程池
	 */
	public static final String COMMON_EXECUTOR = "commonExecutor";

	/**
	 * websocket通信线程池
	 */
	public static final String WS_EXECUTOR = "websocketExecutor";

	public static final String AICHAT_EXECUTOR = "aichatExecutor";

	@Override
	public Executor getAsyncExecutor() {
		return commonExecutor();
	}

	@Bean(COMMON_EXECUTOR)
	@Primary
	public ThreadPoolTaskExecutor commonExecutor() {

		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		executor.setTaskDecorator(new TraceIdTaskDecorator()); // 线程上下文传递
		executor.setCorePoolSize(8); // 设置核心线程数
		executor.setMaxPoolSize(16); // 设置最大线程数
		executor.setKeepAliveSeconds(60); // 设置空闲时间
		executor.setQueueCapacity(100); // 设置队列大小
		executor.setThreadNamePrefix("common-executor-");
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());// 满了调用线程执行，认为重要任务
		executor.setThreadFactory(new MyThreadFactory(executor));
		executor.initialize();
		return executor;
	}

	@Bean(WS_EXECUTOR)
	public ThreadPoolTaskExecutor websocketExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		executor.setCorePoolSize(16);
		executor.setMaxPoolSize(16);
		executor.setQueueCapacity(1000);// 支持同时推送1000人
		executor.setThreadNamePrefix("websocket-executor-");
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());// 满了直接丢弃，默认为不重要消息推送
		executor.setThreadFactory(new MyThreadFactory(executor));
		executor.initialize();
		return executor;
	}

	@Bean(AICHAT_EXECUTOR)
	public ThreadPoolTaskExecutor chatAiExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		executor.setCorePoolSize(10);
		executor.setMaxPoolSize(10);
		executor.setQueueCapacity(15);
		executor.setThreadNamePrefix("aichat-executor-");
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());// 满了直接丢弃，默认为不重要消息推送
		executor.setThreadFactory(new MyThreadFactory(executor));
		return executor;
	}

}
